import 'package:flutter/material.dart';

typedef StarTappedCallback(double percent);

class StarWidget extends StatelessWidget {
  final int count;
  final Color? color;
  final Color backgroundColor;
  final double? size;
  final double percent; //0 ~ 1.0之间的值
  final StarTappedCallback? starTappedCallback;

  const StarWidget({
    Key? key,
    this.count = 5,
    this.color,
    this.backgroundColor = Colors.grey,
    this.size,
    required this.percent,
    this.starTappedCallback,
  }) : super(key: key);

  IconData getIcon(int index) {
    final position = index + 1;
    final value = percent * 5;
    final high = value.ceil();

    if (position < value || position == high) {
      return Icons.star;
    } else {
      return Icons.star_border;
    }
  }

  Color getColor(BuildContext context, int index) {
    final position = index + 1;
    final value = percent * 5;
    final high = value.ceil();

    if (position < value) {
      return color ?? Theme.of(context).primaryColor;
    } else if (position == high) {
      return color ?? Theme.of(context).primaryColor;
    } else {
      return backgroundColor;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(
        count,
        (index) => starTappedCallback == null
            ? Icon(
                getIcon(index),
                color: getColor(context, index),
                size: size,
              )
            : SizedBox(
                width: 28,
                height: 24,
                child: IconButton(
                  padding: EdgeInsets.zero,
                  icon: Icon(
                    getIcon(index),
                    color: getColor(context, index),
                    size: size,
                  ),
                  onPressed: () {
                    starTappedCallback!((index + 1.0) / count);
                  },
                ),
              ),
      ),
    );
  }
}
